package personalfinancemanager;

import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.util.Calendar;
import javax.swing.JLabel;
import javax.swing.table.DefaultTableCellRenderer;

/**
 *
 * @author Geek Squad
 */
public class OverviewPanel extends javax.swing.JPanel {

    /**
     * Creates new form OverviewPanel
     */
    public OverviewPanel() {
        initComponents();
        BudgetNameAndBarPane testBudget = new BudgetNameAndBarPane();
        BudgetNameAndBarPane testBudget2 = new BudgetNameAndBarPane();
        BudgetNameAndBarPane testBudget3 = new BudgetNameAndBarPane();

        budgetsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Budgets", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 0, 24))); // NOI18N
        budgetsPanel.setLayout(new javax.swing.BoxLayout(budgetsPanel, javax.swing.BoxLayout.Y_AXIS));
        budgetsPanel.add(testBudget);
        budgetsPanel.add(testBudget2);
        budgetsPanel.add(testBudget3);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        calendarTable = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        budgetsPanel = new javax.swing.JPanel();
        creditsForMonthLabel = new javax.swing.JLabel();
        debitsForMonthLabel = new javax.swing.JLabel();
        upcomingBillsScrollPanel = new javax.swing.JScrollPane();
        upcomingBillsLabel = new javax.swing.JLabel();
        monthAndYearLabel = new javax.swing.JLabel();
        rightCalendarButton = new javax.swing.JButton();
        leftCalendarButton = new javax.swing.JButton();
        welcomeLoggedInUserLabel = new javax.swing.JLabel();

        calendarTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "S", "M", "T", "W", "T", "F", "S"
            }
        ));
        calendarTable.setCellSelectionEnabled(true);
        calendarTable.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(calendarTable);
        calendarTable.getColumnModel().getColumn(0).setResizable(false);
        calendarTable.getColumnModel().getColumn(1).setResizable(false);
        calendarTable.getColumnModel().getColumn(2).setResizable(false);
        calendarTable.getColumnModel().getColumn(3).setResizable(false);
        calendarTable.getColumnModel().getColumn(4).setResizable(false);
        calendarTable.getColumnModel().getColumn(5).setResizable(false);
        calendarTable.getColumnModel().getColumn(6).setResizable(false);

        budgetsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Budgets", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 0, 24))); // NOI18N
        budgetsPanel.setLayout(new javax.swing.BoxLayout(budgetsPanel, javax.swing.BoxLayout.LINE_AXIS));
        jScrollPane2.setViewportView(budgetsPanel);
        budgetsPanel.getAccessibleContext().setAccessibleDescription("");

        creditsForMonthLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        creditsForMonthLabel.setText("Total Credits for the Month: $0.00");

        debitsForMonthLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        debitsForMonthLabel.setText("Total Debits for the Month: $0.00");

        upcomingBillsScrollPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Upcoming Bills", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 0, 24))); // NOI18N

        upcomingBillsLabel.setText("Electric bill of $0.00 due on 01/01/2014");
        upcomingBillsLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        upcomingBillsScrollPanel.setViewportView(upcomingBillsLabel);

        monthAndYearLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        monthAndYearLabel.setText("September, 2014");

        rightCalendarButton.setText(">>");

        leftCalendarButton.setText("<<");

        welcomeLoggedInUserLabel.setText("Welcome, User!");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(upcomingBillsScrollPanel, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(welcomeLoggedInUserLabel)
                            .addComponent(debitsForMonthLabel)
                            .addComponent(creditsForMonthLabel))
                        .addGap(0, 192, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(leftCalendarButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(monthAndYearLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rightCalendarButton))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addGap(164, 164, 164))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(welcomeLoggedInUserLabel)
                        .addGap(42, 42, 42)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(monthAndYearLabel)
                            .addComponent(leftCalendarButton)
                            .addComponent(rightCalendarButton)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(creditsForMonthLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(debitsForMonthLabel)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addComponent(upcomingBillsScrollPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(294, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Sets a welcome text to the user logged in at the top left.
     *
     * @param user The user name of the current user logged in.
     */
    public void setWelcomeLoggedInUserText(String user) {
        welcomeLoggedInUserLabel.setText("Welcome, " + user + "!");
    }

    public void setCreditsForMonthLabel(BigDecimal amount) {
        creditsForMonthLabel.setText("Total Credits for the Month: $" + amount);
    }

    public void setDebitsForMonthLabel(BigDecimal amount) {
        debitsForMonthLabel.setText("Total Debits for the Month: $" + amount);
    }
    
    public void setUpcomingBillsLabel(String upcomingBills) {
        upcomingBillsLabel.setText(upcomingBills);
    }

    /**
     * Sets the month and year label above the calendar.
     *
     * @param monthAndYear The month and year string that the label will be set
     * to.
     */
    public void setMonthAndYearLabel(String monthAndYear) {
        monthAndYearLabel.setText(monthAndYear);
    }

    /**
     * Sets the calender on the Overview tab to whatever calendarModel's current
     * month is set to.
     *
     * @param calendarModel The calendar model, a custom class which holds a
     * date and allows us to get the max days in the month.
     */
    public void setNumbersForCalendar(CalendarModel calendarModel) {
        DefaultTableCellRenderer textAlignmentRenderer = new DefaultTableCellRenderer(); //Renderer for the text in table cells.
        textAlignmentRenderer.setHorizontalAlignment(JLabel.LEFT); //Horizontal align left.
        textAlignmentRenderer.setVerticalAlignment(JLabel.TOP); //Vertical align top.

        for (int i = 0; i < calendarTable.getColumnCount(); i++) {
            calendarTable.getColumnModel().getColumn(0).setCellRenderer(textAlignmentRenderer); //Set the alignment to top left for the ith column.   
        }

        //Add 1, because the zeller function calculates with months
        //being from 3 - 14.
        int month = calendarModel.getMonth() + 1;
        int year = calendarModel.getYear();

        //If month is 1 or 2, add 12 because the Zeller function
        //only computes months from 3 - 14.
        if (month == 1 || month == 2) {
            month = month + 12;
            //Subtract from the year, because if January or February,
            //we use the 13th or 14th month of the previous year.
            year--;
        }

        //We use Zeller's congruence to calculate the day of the week 0 - 6,
        //which is used to calculate the correct column on the 0th row to start
        //on in the calendar table. The result is stored in firstDayMonthIndex.
        int firstDayInMonthColIndex = calendarModel.zeller(1, month, year % 100, year / 100);

        //Filling in the numbers before the 1st from the previous month.
        Calendar prevMonthCalendar = Calendar.getInstance();
        //Subtract 2 from month for prevMonthCalendar, one because we store the
        //months in the calendar model from 0 - 11, one more to go back to the
        //previous month.
        prevMonthCalendar.set(year, month - 2, 1);
        int daysInPrevMonth = new CalendarModel(prevMonthCalendar).getDaysInMonth();
//        System.out.println("days in month for" + calendarModel.getMonthAndYearForCalendar() + " = " + daysInPrevMonth);

        //Calculating the column index of the previous month's last day.
        //Subtract one because Saturday is indexed as 0 from Zeller's function,
        //and Sunday is 1, Monday is 2, etc., but we want to make the index
        //based on 0 starting with Sunday.
        //Subtract another one because we want the previous column from the
        //first day of the current month.
        int prevMonthLastDayColIdx = firstDayInMonthColIndex - 2;
        //If prevMonthLastDayColIdx happens to be 0 or 1, we will have a
        //negative column index, so add 7 to push it to the correct positive
        //column index.
        if (prevMonthLastDayColIdx < 0) {
            prevMonthLastDayColIdx += 7;
        }
        //This is where the numbers from the previous month are filled.
        for (int i = prevMonthLastDayColIdx; i >= 0; i--) {
            calendarTable.getModel().setValueAt("<html><font color=\"gray\">" + daysInPrevMonth + "</font></html>", 0, i);
            daysInPrevMonth--;
        }

        //Get the total days in the month for the current month we want to
        //display.
        int daysInMonth = calendarModel.getDaysInMonth();
        //This is where the numbers on the calendar are generated. i is the row
        //index, j is the column index.
        int dayOfMonth = 1;
        int i, j = 0;
        for (i = 0; dayOfMonth <= daysInMonth; i++) {
            //The ternary operator sets j to firstDayMonthIndex - 1 only if
            //i = 0, (because columns in the table use 0-based indexing). 
            //This is so the 1st day of the month can be placed in the correct
            //column for the month and year that the calendar model is
            //currently on. Otherwise, j is set to 0 because for subsequent rows
            //of the calendar, we can start printing the days of the month
            //starting from the 0th column.
            for (j = ((i == 0) ? firstDayInMonthColIndex - 1 : 0); j < 7 && (dayOfMonth <= daysInMonth); j++) {
                //The Zeller function represents 0 as Saturday, so if
                //firstDayMonthIndex happened to be 0, j would be calculated as
                //-1, so we add 7 so it will use the correct column number for
                //Saturday, which is 6.
                if (j == -1) {
                    j += 7;
                }

                //If the 1st of the month happens to be on a Sunday, increment i
                //so we start the month on the second row and put the previous
                //month's days on the first row.
                if (i == 0 && j == 0) {
                    i++;
                }

                calendarTable.getModel().setValueAt(dayOfMonth, i, j); //Set the value at row i, column j
                dayOfMonth++;
            }
        }

        //Filling the rest of the calendar after the last day of the current
        //month in gray.
        //Decrement i by 1, because we want to began filling the next month's
        //dates starting on the same row where the current month's dates left
        //off.
        i--;
        dayOfMonth = 1;
        for (; i < 6; i++) {
            for (; j < 7; j++) {
                calendarTable.getModel().setValueAt("<html><font color=\"gray\">" + dayOfMonth + "</font></html>", i, j);
                dayOfMonth++;
            }
            j = 0;
        }
    }

    /**
     * Clears all the dates in the calendar table.
     */
    public void resetCalendar() {
        for (int i = 0; i < calendarTable.getRowCount(); i++) {
            for (int j = 0; j < calendarTable.getColumnCount(); j++) {
                calendarTable.getModel().setValueAt("", i, j);
            }
        }
    }

    //Adding action listeners
    void addLeftCalendarButtonListener(ActionListener al) {
        leftCalendarButton.addActionListener(al);
    }

    void addRightCalendarButtonListener(ActionListener al) {
        rightCalendarButton.addActionListener(al);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel budgetsPanel;
    private javax.swing.JTable calendarTable;
    private javax.swing.JLabel creditsForMonthLabel;
    private javax.swing.JLabel debitsForMonthLabel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton leftCalendarButton;
    private javax.swing.JLabel monthAndYearLabel;
    private javax.swing.JButton rightCalendarButton;
    private javax.swing.JLabel upcomingBillsLabel;
    private javax.swing.JScrollPane upcomingBillsScrollPanel;
    private javax.swing.JLabel welcomeLoggedInUserLabel;
    // End of variables declaration//GEN-END:variables
}
